package cn.doitedu.webserver;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class Demo {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8080);

        // 初始化各功能处理器
        HashMap<String, HttpServlet> servlets = new HashMap<>();
        servlets.put("/login",new LoginServlet());
        servlets.put("/order",new SubmitOrderServlet());
        servlets.put("/error",new ErrorServlet());


        while(true) {
            // 接收连接
            Socket socket = serverSocket.accept();

            InputStream in = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            OutputStream out = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));


            // 获取浏览器请求头信息
            // 第一行是这样：  GET /add_exp?a=1 HTTP/1.1
            String line = br.readLine();
            System.out.println(line);

            // GET /add_exp?a=1 HTTP/1.1
            String[] split = line.split(" ")[1].split("\\?");
            String path = split[0];

            // 根据客户端所请求的功能路径，取功能处理器map中获取对应的处理器
            HttpServlet servlet = servlets.getOrDefault(path,new ErrorServlet());


            // 准备公共响应头
            StringBuilder sb = new StringBuilder();
            sb.append("HTTP/1.1 200 OK\r\n");
            sb.append("Content-Type: text/html;charset=utf-8\r\n");

            // 调用处理器进行处理
            servlet.doGet(sb);

            // 再把处理器拼接好的整个http响应，返回给浏览器
            pw.println(sb.toString());

            pw.close();
            br.close();
            in.close();
            out.close();
            socket.close();

        }

    }
}
